import time
from PyQt5 import QtCore

from .baidu import Baidu


def timestamp2str(timestamp):
    timeStamp = float(timestamp / 1000)
    timeArray = time.localtime(timeStamp)
    time_str = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    return time_str


class BdGeocoder(QtCore.QThread):
    result_signal = QtCore.pyqtSignal(dict)
    progress_signal = QtCore.pyqtSignal(str)
    error_signal = QtCore.pyqtSignal(str)
    finished_signal=QtCore.pyqtSignal(str)

    def __init__(self, points_str, ak=None):
        super(BdGeocoder, self).__init__()
        self.points_str = points_str

        self.ak = ak
        self.geocoder = Baidu(api_key=self.ak,
                              timeout=200
                              )

    def run(self):
        self.progress_signal.emit("正在解析经纬度数据！")
        gc = self.geocoder
        points = eval(self.points_str)
        try:
            for point in points:
                p_str = "%s,%s" % (point['lat'], point['lon'])
                rev_location = gc.reverse(p_str)
                position_time = point.get("positionTime")
                if isinstance(position_time, (int, float)):
                    position_time = timestamp2str(position_time)
                location = rev_location.raw
                location['position_time'] = position_time
                self.result_signal.emit(location)
                self.progress_signal.emit("当前解析出的地址:%s" % location['formatted_address'])
            self.progress_signal.emit("本次解析已完成!去点击轨迹回放看看吧！")
        except Exception as e:
            self.error_signal.emit("解析经纬度时出错了!检查下是不是断网了呢?\n错误详情:%s" % e)
        finally:
            self.finished_signal.emit("done")
            time.sleep(3)
            self.progress_signal.emit("done")
